<?php

/**
 * toefl API
 * Created by PhpStorm.
 * User: obelisk
 */

namespace app\modules\app\controllers;

use app\modules\app\models\IeltsSpeakLike;
use app\modules\app\models\IntegralBuy;
use app\modules\app\models\UserPlan;
use app\modules\cn\models\ExerciseResult;
use app\modules\content\models\Active;
use app\modules\content\models\IeltsVersion;
use app\modules\content\models\Popup;
use app\modules\content\models\VideoLog;
use yii;
use app\libs\AppControl;
use app\libs\Method;
use app\libs\Pager;
use app\libs\VerificationCode;
use app\libs\Sms;
use app\modules\cn\models\ResourcesPhone;
use app\modules\cn\models\HotActive;
use app\modules\content\models\Banner;
use app\modules\content\models\Ad;
use app\modules\content\models\IeltsWrite;
use app\modules\content\models\IeltsWriteAnswer;
use app\modules\content\models\Classes;
use app\modules\content\models\IeltsSpeak;
use app\modules\content\models\IeltsSpeakList;
use app\modules\content\models\IeltsSpeakAnswer;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

class ApiController extends AppControl
{

    public $enableCsrfValidation = false;

    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

    /**
     * [actionAppHome 雅思app首页]
     * @Author don
     * @Date   2022-03-04
     * @return [type]     [description]
     */
    public function actionAppHome()
    {
        $data = [];
        $uid = Yii::$app->session->get('uid');
        // banner
        $data['banner'] = Banner::find()->asArray()->limit(5)->where("cate=1 and type=3")->orderBy('sort asc,id desc')->all();
        // 热门活动
        $data['hotActive'] = HotActive::find()->select('id,title,pic,reservations,startTime,endTime,cate,sdk,free,integral')->where(['type'=>1])->orderBy('sort asc')->limit(2)->asArray()->all();
        if ($data['hotActive']) {
            $data['hotActive'] = HotActive::activeDeal($data['hotActive'],$uid);
        }

        // 广告
        $data['ad'] = Ad::find()->where(['cate'=>2, 'type'=>1])->asArray()->one();

        // 推荐课程
        $data['recommendCourse'] = Classes::find()->where(['showType'=>1,'classesPort'=>2])->orderBy('sort asc,id desc')->limit(2)->asArray()->all();
        if ($data['recommendCourse']) {
            foreach ($data['recommendCourse'] as $recommend_key => $recommend_value) {
                $data['recommendCourse'][$recommend_key]['course_tag'] = !empty($recommend_value['course_tag'])?explode(',', $recommend_value['course_tag']):null;
            }
        }
        //公开课
        $data['openCourse'] = Classes::getCourse(6,2);
        $data['question']= ExerciseResult::question();
        $data['plan'] = $uid != false ? UserPlan::find()->asArray()->where('uid=' . $uid)->orderBy('id desc')->one() : '';
        $data['status'] = $data['plan'] == false ? 0 : 1;
        //弹窗
        $time = time();
        $data['popup'] = Popup::find()->where("startTime<=$time and endTime>=$time and port=1 and belong=1")->asArray()->orderBy('id desc')->one();
        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    /**
     * [actionHotActive 首页热门活动]
     * @Author don
     * @Date   2021-12-15
     * @return [type]     [description]
     */
    public function actionHotActive()
    {
        $limit = Yii::$app->request->post('limit', 2);
        $data = HotActive::find()->select('id,title,pic,reservations')->where(['type'=>1])->orderBy('sort asc')->limit($limit)->asArray()->all();
        if (!$data) {
            die(json_encode(['code'=>0, 'message'=>'暂未找到热门活动！']));
        }
        // 真是报名人数和假报名人数count
        $data = HotActive::getReservation($data);
        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    /**
     * [actionHotActiveDetail 热门活动详情]
     * @Author don
     * @Date   2021-12-15
     * @return [type]     [description]
     */
    public function actionHotActiveDetail()
    {
        $uid = Yii::$app->session->get('uid',0);
        $id = Yii::$app->request->post('id');
        // $uid = 3;
        $data = HotActive::find()->where(['id'=>$id])->asArray()->one();

        if (!$data) {
            die(json_encode(['code'=>0, 'message'=>'暂未找到热门活动！']));
        }
        $data = HotActive::activeDeal(array($data),$uid)[0];
        // 真是报名人数和假报名人数count
        $data = HotActive::getSingleReservation($data);

        // 更新浏览量
        HotActive::updateAll(['viewCount' => ($data['viewCount'] + 1)], "id=$id");
        // 如果用户已登录，查询是否报名
//        $data['isCheck'] = 0;
//        if ($uid) {
//            $tmp = ResourcesPhone::checkResource($uid, $data['title']);
//            if ($tmp) {
//                $data['isCheck'] = 1;
//            }
//        }
        $data['startTime']= date('Y-m-d',strtotime($data['startTime']));
        $data['endTime']= date('Y-m-d',strtotime($data['endTime']));
        //视频列表
        $video = [];
        if($data['video']==1){
            $video[0] = [
                'sdkId' => $data['id'],
                'name' => $data['title'],
                'videoUrl' => $data['sdk'],
                'image' => $data['image']?Yii::$app->params['thinkUrl'].$data['pic']:'',
                'integral' => $data['integral'],
                'free' => $data['free'],
                'isBuy' => $data['isBuy'],
                'record' => VideoLog::getVideoRecord($id, $uid,3)
            ];
        }
        $data['videos'] = $video;
        die(json_encode(['code'=>1, 'data'=>$data]));
    }


    /**
     * [actionReportResources 预约报名]
     * @Author don
     * @Date   2021-12-15
     * @return [type]     [description]
     */
    public function actionReportResources()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid = 3;
        $phone = Yii::$app->request->post('phone');
        $remark = Yii::$app->request->post('remark');
        $model = new ResourcesPhone();
        $model->uid = $uid;
        $model->phone = $phone;
        $model->type = 3;
        $model->createTime = time();
        $model->remark = $remark;
        if (!$model->save()) {
            die(json_encode(['code' => 0, 'message' => '报名失败！']));
        }

        die(json_encode(['code' => 1, 'message' => '报名成功！']));
    }

    /**
     * [actionHotActiveList 雅思活动列表]
     * @Author don
     * @Date   2022-03-04
     * @return [type]     [description]
     */
    public function actionHotActiveList()
    {
        $page = Yii::$app->request->post('page', 1);
        $pageSize = 10;
        $offset = ($page - 1) * $pageSize;
        // 获取置顶活动没有则为空
        $data['topActive'] = HotActive::find()->where(['isTop'=>1])->orderBy('id desc')->asArray()->one();
        $data['list'] = HotActive::find()->orderBy('sort asc')->offset($offset)->limit($pageSize)->asArray()->all();
        $count = HotActive::find()->count();
        $totalPage = ceil($count / $pageSize);
        $uid = Yii::$app->session->get('uid');

        if ($data['list']) {
            $data['list'] = HotActive::activeDeal($data['list'],$uid);
        }
        
        die(json_encode(['code'=>1, 'data'=>$data, 'totalPage'=>$totalPage]));
    }

    /**
     * [actionIeltsWrite 写作机经]
     * @Author don
     * @Date   2022-03-07
     * @return [type]     [description]
     */
    public function actionIeltsWrite()
    {
        $year = Yii::$app->request->post('year', 2022);
        $month = Yii::$app->request->post('month');
        $page = Yii::$app->request->post('page', 1);
        $pageSize = 10;
        $offset = ($page - 1) * $pageSize;
        if (!$month) {
            $month = date('n');
        }
        $data = IeltsWrite::find()->where(['year'=>$year, 'month'=>$month])->orderBy('id desc')->offset($offset)->limit($pageSize)->asArray()->all();
        $count = IeltsWrite::find()->where(['year'=>$year, 'month'=>$month])->count();
        $totalPage = ceil($count / $pageSize);
        $months = [];
        $res = IeltsWrite::find()->select('month')->where(['year'=>$year])->groupBy('month')->orderBy('month desc')->asArray()->all();
        if ($res) {
            foreach ($res as $key => $value) {
                $months[] = $value['month'];
            }
        }
        // 如果默认当前月份没有题目数据，则显示最近一个月的写作数据
        if (!$data) {
            if ($months) {
                $data = IeltsWrite::find()->where(['year'=>$year, 'month'=>$months[0]])->orderBy('id desc')->offset($offset)->limit($pageSize)->asArray()->all();
                $count = IeltsWrite::find()->where(['year'=>$year, 'month'=>$months[0]])->count();
                $totalPage = ceil($count / $pageSize);
            } else {
                $data = [];
                $count = $totalPage = 0;
            }
        }
        // 判断用户是否答过题
        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k]['status'] = IeltsWriteAnswer::isSubmit($v['id']);
            }
        }
        // 年份列表
        $years = ['2022'];
        die(json_encode(['code'=>1, 'data'=>$data, 'count'=>$count, 'totalPage'=>$totalPage, 'years'=>$years, 'months'=>$months]));
    }

    public function actionIeltsWriteNew(){
        $year = Yii::$app->request->post('year', 2022);
        $data['part1'] = IeltsWrite::find()->where(['year'=>$year, 'part'=>1])->orderBy('updateTime desc,id desc')->asArray()->all();
        $data['part1'] = IeltsWrite::writeData($data['part1']);
        $data['part2'] = IeltsWrite::find()->where(['year'=>$year, 'part'=>2])->orderBy('updateTime desc,id desc')->asArray()->all();
        $data['part2'] = IeltsWrite::writeData($data['part2']);
        // 年份列表
        $years = ['2022'];
        die(json_encode(['code'=>1, 'data'=>$data, 'years'=>$years,]));
    }

    /**
     * [actionIeltsWriteDetail 写作机经详情]
     * @Author don
     * @Date   2022-03-07
     * @return [type]     [description]
     */
    public function actionIeltsWriteDetail()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid=3;
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'请先登录']));
        }
        $id = Yii::$app->request->post('id');
        $data = IeltsWriteAnswer::find()->where(['pid'=>$id, 'uid'=>$uid])->asArray()->one();
        // 广告
        $ad = Ad::find()->where(['cate'=>2, 'type'=>1])->asArray()->one();
        die(json_encode(['code'=>1, 'data'=>$data, 'ad'=>$ad]));
    }

    /**
     * [actionSubmitIeltsWrite 提交写作]
     * @Author don
     * @Date   2022-03-07
     * @return [type]     [description]
     */
    public function actionSubmitIeltsWrite()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid=3;
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'请先登录']));
        }
        $id = Yii::$app->request->post('id');
        $user_answer = Yii::$app->request->post('user_answer');
        if (empty($user_answer)) {
            die(json_encode(['code'=>0, 'message'=>'请输入内容']));
        }
        $tmp = IeltsWriteAnswer::find()->where(['pid'=>$id, 'uid'=>$uid])->asArray()->one();
        if ($tmp) {
            $model = IeltsWriteAnswer::findOne($tmp['id']);
            $model->user_answer = $user_answer;
            $model->updateTime = time();
            if (!$model->save()) {
                die(json_encode(['code'=>0, 'message'=>'提交失败！']));
            }
        } else {
            $model = new IeltsWriteAnswer();
            $model->pid = $id;
            $model->uid = $uid;
            $model->user_answer = $user_answer;
            $model->createTime = time();
            $model->updateTime = time();
            if (!$model->save()) {
                die(json_encode(['code'=>0, 'message'=>'提交失败！']));
            }
        }

        die(json_encode(['code'=>1, 'message'=>'提交成功！']));
    }

    /**
     * [actionDelIeltsWrite 删除写作]
     * @Author don
     * @Date   2022-03-07
     * @return [type]     [description]
     */
    public function actionDeleteIeltsWrite()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid=3;
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'请先登录']));
        }
        $id = Yii::$app->request->post('id');

        $re = IeltsWriteAnswer::deleteAll("pid=:pid and uid=:uid", array(':pid' => $id, ':uid'=>$uid));
        if (!$re) {
            die(json_encode(['code'=>0, 'message'=>'删除失败！']));
        }

        die(json_encode(['code'=>1, 'message'=>'删除成功！']));
    }

    /**
     * [actionSpeak 口语真题]
     * @Author don
     * @Date   2022-03-08
     * @return [type]     [description]
     */
    public function actionIeltsSpeak()
    {
        $nowMonth = date('n');
        if ($nowMonth >= 1 && $nowMonth <= 4) {
            $month = 1; // 1-4月
        } elseif ($nowMonth >= 5 && $nowMonth <= 8) {
            $month = 2; // 5-8月
        } else {
            $month = 3; // 9-12月
        }
        $year = date('Y');

        $data['part1'] = IeltsSpeak::find()->where(['year'=>$year, 'month'=>$month, 'part'=>1])->orderBy('sort desc,id desc')->asArray()->all();
        $data['part23'] = IeltsSpeak::find()->where(['year'=>$year, 'month'=>$month, 'part'=>2])->orderBy('sort desc,id desc')->asArray()->all();
        $data['past1'] = IeltsSpeak::pastSpeak($year,$month,1);
        $data['past23'] = IeltsSpeak::pastSpeak($year,$month,2);
        if($month==1){
            $month='1-4';
        }elseif($month==2){
            $month='5-8';
        }else{
            $month='9-12';
        }
        die(json_encode(['code'=>1, 'data'=>$data, 'year'=>$year, 'month'=>$month]));
    }

    /**
     * [actionIeltsSpeakList 口语话题列表]
     * @Author don
     * @Date   2022-03-08
     * @return [type]     [description]
     */
    public function actionIeltsSpeakList()
    {
        $type = Yii::$app->request->post('type', 1); // 1:part1 2:part2&3
        $id = Yii::$app->request->post('id');
        if ($type == 1) {
            $data = IeltsSpeakList::find()->where(['pid'=>$id, 'part'=>1])->orderBy('id asc')->asArray()->all();
            $tag = IeltsSpeak::getSpeakType($data);
        } else {
            $data['part2'] = IeltsSpeakList::find()->where(['pid'=>$id, 'part'=>2])->orderBy('id asc')->asArray()->all();
            $data['part3'] = IeltsSpeakList::find()->where(['pid'=>$id, 'part'=>3])->orderBy('id asc')->asArray()->all();
            $arr = $data['part2']?$data['part2']:$data['part3'];
            $tag = IeltsSpeak::getSpeakType($arr);
        }

        die(json_encode(['code'=>1, 'data'=>$data,'tag'=>$tag]));
    }

    /**
     * [actionIeltsSpeakDetail 口语题目详情]
     * @Author don
     * @Date   2022-03-08
     * @return [type]     [description]
     */
    public function actionIeltsSpeakDetail()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid=3;
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'请先登录']));
        }
        $id = Yii::$app->request->post('id');
        $data = IeltsSpeakList::find()->where(['id'=>$id])->asArray()->one();
        $data = IeltsSpeakLike::getLikeNum(array($data),$uid,2)[0];
        if(!empty($data['audio'])) $data['audio'] = Yii::$app->params['thinkUrl'].$data['audio'];
        $data['teacherImg'] = Yii::$app->params['defaultImg'];//老师默认头像
        $fid = $data['pid'];
        $userAnswer = IeltsSpeakAnswer::find()->where(['uid'=>$uid, 'fid'=>$fid, 'pid'=>$id])->asArray()->one();
        if($userAnswer){
            //更改为已读
            IeltsSpeak::changeStatus($uid,$userAnswer['id']);
            $userAnswer = IeltsSpeakLike::getLikeNum(array($userAnswer),$uid,1)[0];
        }
        //其它用户答案
        $otherAnswer = IeltsSpeakAnswer::find()->where("uid!=$uid and fid=$fid and pid=$id and status=1")->asArray()->orderBy('id desc')->limit(5)->all();
        if($otherAnswer) $otherAnswer = IeltsSpeakLike::getLikeNum($otherAnswer,$uid,1);
        // 广告
        $ad = Ad::find()->where(['cate'=>2, 'type'=>1])->asArray()->one();
        //所有题
        $list = IeltsSpeakList::find()->select('id')->where("pid=$fid")->orderBy('part asc,id asc')->asArray()->all();
        //题目数量
        $count = count($list);
        //当前位置
        $listId = array_column($list,'id');
        $site = array_search($id,$listId);
        if($count<=1){
            $prev = $next = 0;
        }elseif($site==$count-1){
            //最后一题
            $prev = $listId[$site-1];
            $next = 0;
        }elseif($site==0){
            //第一题
            $prev = 0;
            $next = $listId[$site+1];
        }else{
            $prev = $listId[$site-1];
            $next = $listId[$site+1];
        }

        die(json_encode(['code'=>1, 'data'=>$data, 'ad'=>$ad, 'userAnswer'=>$userAnswer,'otherAnswer'=>$otherAnswer,'prev'=>$prev,'next'=>$next,'count'=>$count,'now'=>$site+1]));
    }

    /**
     * [actionSubmitIeltsSpeak 提交口语真题]
     * @Author don
     * @Date   2022-03-11
     * @return [type]     [description]
     */
    public function actionSubmitIeltsSpeak()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid=3;
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'请先登录']));
        }

        $id = Yii::$app->request->post('id');
        $path = Yii::$app->request->post('path');
        $status = Yii::$app->request->post('status',1);//1公开 2私密
        $data = IeltsSpeakList::find()->where(['id'=>$id])->asArray()->one();
        $fid = $data['pid'];
        // 查询是否有记录
        $res = IeltsSpeakAnswer::find()->where(['uid'=>$uid, 'fid'=>$fid, 'pid'=>$id])->asArray()->one();
        if (!$res) {
            $model = new IeltsSpeakAnswer();
            $model->fid = $fid;
            $model->pid = $id;
            $model->uid = $uid;
            $model->user_answer = $path;
            $model->status = $status;
            $model->createTime = time();
            if (!$model->save()) {
                die(json_encode(['code'=>0, 'message'=>'提交失败！']));
            }
        } else {
            $model = IeltsSpeakAnswer::findOne($res['id']);
            $model->user_answer = $path;
            $model->status = $status;
            if (!$model->save()) {
                die(json_encode(['code'=>0, 'message'=>'提交失败！']));
            }
        }
        
        die(json_encode(['code'=>1, 'message'=>'提交成功！']));
    }

    /**
     * [actionDelIeltsWrite 删除写作]
     * @Author don
     * @Date   2022-03-07
     * @return [type]     [description]
     */
    public function actionDeleteIeltsSpeak()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid=3;
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'请先登录']));
        }
        $id = Yii::$app->request->post('id');

        $re = IeltsSpeakAnswer::deleteAll("id=:id", array(':id' => $id));
        if (!$re) {
            die(json_encode(['code'=>0, 'message'=>'删除失败！']));
        }

        die(json_encode(['code'=>1, 'message'=>'删除成功！']));
    }

    /**
     * [actionDelIeltsWrite 删除写作]
     * @Author yoyo
     * @Date   2022-04-20
     * @return [type]     [description]
     */
    public function actionIeltsVersion()
    {
        $data= IeltsVersion::find()->asArray()->orderBy('id desc')->one();
        if($data==false){
            die(json_encode(['code'=>0, 'message'=>'暂无更新！']));
        }
        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    /**
     * 口语做题答案点赞
     */
    public function actionIeltsSpeakLike(){
        $uid = Yii::$app->session->get('uid');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'请先登录']));
        }
        $id = Yii::$app->request->post('id');
        $type = Yii::$app->request->post('type');
        $check = IeltsSpeakLike::find()->where("contentId=$id and type=$type and uid=$uid")->one();
        if($check){
            $res = IeltsSpeakLike::deleteAll("id={$check->id}");
            if($res){
                die(json_encode(['code'=>1, 'message'=>'取消成功']));
            }else{
                die(json_encode(['code'=>0, 'message'=>'取消失败']));
            }
        }else{
            $model = new IeltsSpeakLike();
            $model->uid = $uid;
            $model->contentId = $id;
            $model->type = $type;
            $model->createTime = time();
            $res = $model->save();
            if($res){
                die(json_encode(['code'=>1, 'message'=>'点赞成功']));
            }else{
                die(json_encode(['code'=>0, 'message'=>'点赞失败']));
            }
        }
    }

    /**
     * 口语音频状态设置
     */
    public function actionIeltsSpeakStatus(){
        $uid = Yii::$app->session->get('uid');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'请先登录']));
        }
        $id = Yii::$app->request->post('id');
        $status = Yii::$app->request->post('status');
        $res = IeltsSpeakAnswer::updateAll(['status'=>$status],"id=$id and uid=$uid");
        if($res){
            die(json_encode(['code'=>1, 'message'=>'操作成功']));
        }else{
            die(json_encode(['code'=>0, 'message'=>'操作失败']));
        }
    }

    /**
     * 考试回忆标签
     */
    public function actionIeltsSpeakTag(){
        $nowMonth = date('n');
        if ($nowMonth >= 1 && $nowMonth <= 4) {
            $month = 1; // 1-4月
        } elseif ($nowMonth >= 5 && $nowMonth <= 8) {
            $month = 2; // 5-8月
        } else {
            $month = 3; // 9-12月
        }
        $year = date('Y');
        //新题
        $data['part1'] = IeltsSpeak::find()->select('cate_name')->where(['year'=>$year, 'month'=>$month, 'part'=>1])->orderBy('sort desc,id desc')->asArray()->column();
        $data['part2'] = IeltsSpeak::find()->select('cate_name')->where(['year'=>$year, 'month'=>$month, 'part'=>2])->orderBy('sort desc,id desc')->asArray()->column();
        array_unshift($data['part1'],'疑似新题');
        array_unshift($data['part2'],'疑似新题');
        //保留题
        $past1 = IeltsSpeak::pastSpeak($year,$month,1);
        if($past1){
            $past1 = array_column($past1,'cate_name');
            $data['part1'] = array_merge($data['part1'],$past1);
        }
        $past2 = IeltsSpeak::pastSpeak($year,$month,2);
        if($past2){
            $past2 = array_column($past2,'cate_name');
            $data['part2'] = array_merge($data['part2'],$past2);
        }
        die(json_encode(['code'=>1, 'message'=>'success','data'=>$data]));
    }

    /**
     * 是否考试计划
     */
    public function actionIsPlan()
    {
        $uid = Yii::$app->request->get('uid');
        if ($uid == false || !is_numeric($uid)) {
            die(json_encode(['code' => 1, 'message' => 'success', 'data' =>'']));
        }
        $data = UserPlan::find()->asArray()->where('uid=' . $uid)->orderBy('id desc')->one() ;
        die(json_encode(['code' => 1, 'message' => 'success', 'data' => $data]));
    }
}
